package cn.itsource.system.service.impl;

import cn.itsource.system.domain.Menu;
import cn.itsource.system.mapper.MenuMapper;
import cn.itsource.system.service.IMenuService;
import cn.itsource.basic.service.impl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 业务实现类：
 */
@Service
public class MenuServiceImpl extends BaseServiceImpl<Menu> implements IMenuService {
    @Autowired
    private MenuMapper menuMapper;
    @Override
    public List<Menu> getMenuTree() {
        List<Menu> menus = menuMapper.findAll();
        List<Menu> result = new ArrayList<>();
        Map<Long, Menu> collect = menus.stream().collect(Collectors.toMap(e-> e.getId(), e -> e));
        for (Menu d:menus) {
            if(null != d.getParentId()){
                //说明它有父亲
                Menu parent = collect.get(d.getParentId());
                if(parent!=null){//有可能父亲还没有被添加进数据库
                    parent.getChildren().add(d);
                }
            }else{
                result.add(d);
            }
        }
        return result;
    }
}
